package com.bw.server.vm

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.blankj.utilcode.util.GsonUtils
import com.bw.common.entity.BaseRes
import com.bw.common.vm.BaseViewModel
import com.bw.server.entity.AddDeviceEntity
import com.bw.server.entity.AddDeviceEntityNull
import com.bw.server.entity.DetailDeviceEntity
import com.bw.server.entity.DeviceEntityItem
import com.bw.server.entity.DeviceStartEntity
import com.bw.server.entity.TransferInspectionEntity
import com.bw.server.model.ServerRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import javax.inject.Inject

@HiltViewModel
class ServerViewModel @Inject constructor(private val repo:ServerRepository):BaseViewModel(){

    //定义LiveData缓存数据
    val mSuccess = MutableLiveData<List<DeviceEntityItem>>()
    fun getDeviceData(){
        //启动子线程 并运行协程
        viewModelScope.launch(mDispatcher) {
            //调用仓库方法获取数据
            val res = repo.loadDeviceData()
            if (res.code == 200){
                mSuccess.postValue(res.data)
            }else{
                mError.postValue("请求失败${res.message}")
            }

        }
    }
    val mAddSuccess = MutableLiveData<AddDeviceEntity>()

    fun addDevice(entity: AddDeviceEntityNull){
        //启动子线程 并运行协程
        viewModelScope.launch(mDispatcher) {
            val res = repo.loadAddDeviceData(entity)

            if (res.code == 200){
                mAddSuccess.postValue(res.data)
            }else{
                mError.postValue("请求失败${res.message}")
            }

        }
    }

    val mDetailSuccess = MutableLiveData<DetailDeviceEntity>()
    fun getDetailData(id:Int){
        viewModelScope.launch(mDispatcher) {
            val res = repo.loadDetailData(id)
            if (res.code ==200){
                mDetailSuccess.postValue(res.data)
            }else{
                mError.postValue("请求失败${res.message}")
            }
        }
    }

    //开始巡检
    val mStartSuccess = MutableLiveData<DeviceStartEntity>()
    fun startInspection(id:Int){
        viewModelScope.launch(mDispatcher) {
            val res = repo.loadStartInspectionData( id)
            if (res.code ==200){
                mStartSuccess.postValue(res.data)
            }else{
                mError.postValue("请求失败${res.message}")
            }
        }
    }


    //转派
    val mTransferSuccess = MutableLiveData<TransferInspectionEntity>()
    fun transfer(id:Int,inspector:String){
        viewModelScope.launch(mDispatcher) {
            val res = repo.loadTransferInspectionData(id,inspector)
            if (res.code ==200){
                mTransferSuccess.postValue(res.data)
            }else{
                mError.postValue("请求失败${res.message}")
            }
        }
    }
}